﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Random = UnityEngine.Random;
public class KnapsackExample:MonoBehaviour
{
    KnapsackComponent knapsackComponent = new KnapsackComponent();
    [SerializeField] ScrollRect scrollRect;
    [SerializeField]DynamicInfinityListRenderer dynamicInfinityListRenderer;

    private void Awake()
    {
        knapsackComponent.Initialize(dynamicInfinityListRenderer);
        knapsackComponent.onUpdate += OnUpdate;
        knapsackComponent.onSelect += OnSelect;

        List<Config> configs = new List<Config>();
        for (int i = 0; i < 5; i++)
        {
            configs.Add(new Config
            {
                id = 10000+i,
                title = i.ToString(),
                isSuperposition = Random.Range(0,100)>50
            }) ;
        }

        IKnapsackItem[] data = new IKnapsackItem[100];
        
        for(int i=0;i<100;i++)
        {
            var config = configs[Random.Range(0,5)];
            data[i] = new Data
            {
                id = config.id,
                title = config.title,
                isSuperposition = config.isSuperposition,
                number = 1
            };
        }

        knapsackComponent.AddRange(data);
    }

    void OnSelect(IKnapsackItem item)
    {
        var data = item as Data;
        Debug.LogError($"{data.GetId()}----{data.GetFixedId()}----{data.GetItemId()}---{data.title}");
    }

    private void OnUpdate(DynamicInfinityItem item)
    {
        var rc = item.GetComponent<ReferenceCollector>();
        var data = item.GetData<Data>();
        rc.GetText("title").text = data.title;
        rc.GetText("number").text = data.GetNumber().ToString();
        var el = EventListener.Get(item.gameObject);
        el.onClick = e => item.OnSelectHandler(item);
        el.onDoubleClick = e => knapsackComponent.Remove(data);
        el.onBeginDrag = scrollRect.OnBeginDrag;
        el.onDrag = scrollRect.OnDrag;
        el.onEndDrag = scrollRect.OnEndDrag;
    }

    public class Data:KnapsackItem
    {
        public string title;
    }
    public class Config
    {
        public int id;
        public string title;
        public bool isSuperposition;
    }
}